﻿using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace FileUpload.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileController : ControllerBase
    {

        [DisableRequestSizeLimit]
        [HttpPost]
        public IActionResult Upload()
        {
            var files = Request.Form.Files;
            long size = files.Sum(f => f.Length);

            string contentRootPath = AppContext.BaseDirectory;
            List<string> filenames = new List<string>();
            foreach (IFormFile formFile in files)
            {
                if (formFile.Length > 0)
                {
                    string fileExt = Path.GetExtension(formFile.FileName);
                    long fileSize = formFile.Length;
                    string newFileName = System.Guid.NewGuid().ToString() + fileExt;
                    var filePath = contentRootPath + "/fileUpload/";
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    using (var stream = new FileStream(filePath + newFileName, FileMode.Create))
                    {
                        formFile.CopyTo(stream);
                    }
                    filenames.Add(newFileName);
                }
            }

            return Ok(filenames);
        }
    }
}
